import 'package:flutter/material.dart';

class LifeApp extends StatelessWidget {
  // 2. 设置默认值
  const LifeApp({
    super.key,
    this.title = '',
    this.content = '',
    this.tColor = Colors.orange,
    this.cColor = Colors.yellow,
  });

  // 1. 定义属性
  final String title;
  final String content;
  final Color tColor;
  final Color cColor;

  // 重写build 返回需要封装的组件即可
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.purple,
          title: Center(
            child: Text(
              '标题为:$title',
              style: TextStyle(
                  color: tColor, fontSize: 30, fontWeight: FontWeight.w900),
            ),
          ),
        ),
        // 1.2 主体部分
        body: const Center(
          child: MyStateWidget(),
        ),
      ),
    );
  }
}

// 1. 继承自StatefulWidget
class MyStateWidget extends StatefulWidget {
  const MyStateWidget({super.key});

  @override
  // 1. 创建组件时调用
  // ignore: no_logic_in_create_state
  // 不建议在 createState 添加逻辑，所以最早的逻辑写到 initState
  State<MyStateWidget> createState() {
    debugPrint('createState-run');
    return _MyStateWidgetState();
  }
}

class _MyStateWidgetState extends State<MyStateWidget> {
  int count = 0;

  @override
  // 2. 组件被初始化时调用
  // 一般用于: 对组件变量赋值, 请求网络数据, 更新状态
  void initState() {
    super.initState();
    debugPrint('initState-run');
  }

  @override
  // 3. 状态组件的依赖项发生变化时调用
  // 只会被执行1次
  void didChangeDependencies() {
    super.didChangeDependencies();
    debugPrint('didChangeDependencies-run');
  }

  @override
  void didUpdateWidget(covariant MyStateWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    debugPrint('didUpdateWidget-run');
  }

  @override
  // 5. 组件即将销毁时自动调用的
  void deactivate() {
    debugPrint('deactivate-run');
    super.deactivate();
  }

  // 6. 组件销毁时自动调用的
  @override
  void dispose() {
    debugPrint('dispose-run');
    super.dispose();
  }

  @override
  // 4. 组件状态更新时自动调用
  // 会调用多次
  Widget build(BuildContext context) {
    debugPrint('build-run');
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        ElevatedButton(
          onPressed: () {
            debugPrint('123');
            setState(() {
              // 修改状态变量
              count--;
            });
          },
          child: const Text('递减'),
        ),
        Text(
          '个数为:$count',
          style: const TextStyle(fontSize: 30, fontWeight: FontWeight.w900),
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              count++;
            });
          },
          child: const Text('累加'),
        ),
      ],
    );
  }
}
